package com.jlt.baidu.controllers;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.jlt.baidu.dto.FileOcrModel;
import com.jlt.baidu.service.BaiduOcrService;

import lombok.extern.slf4j.Slf4j;

/**
 * 文字识别demo
 * 
 * @author Ives.Chen
 *
 */
@Slf4j
@RestController
@RequestMapping("/baidu")
public class OcrBaiduDemoController {
    // 调用百度提供的API
    @Autowired
    BaiduOcrService ocrService;
    @Value("${upload.path}")
    private String uploadPath;

    public String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, Object> springUpload(HttpServletRequest request) throws IllegalStateException, IOException {
        long start = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        // 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        List<FileOcrModel> models = new ArrayList<>();
        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 一次遍历所有文件
                List<MultipartFile> files = multiRequest.getFiles(iter.next().toString());
                for (MultipartFile file : files) {
                    if (file != null) {
                        // 上传
                        models.add(save(file));
                    }
                }
            }
        }
        List<FileOcrModel> results = ocrService.disReceiptForUnderline(models);
        Map<String, Object> map = new HashMap<>();
        for (FileOcrModel fileOcrModel : results) {
            if (fileOcrModel.getDiscernResult().equals(0)) {
                map.put("contents", fileOcrModel.getSuccessResult());
            } else {
                map.put("contents", fileOcrModel.getFailReasons());
            }
        }
        long end = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        System.out.println("百度执行时间：" + (end - start));
        return map;
    }

    public FileOcrModel save(MultipartFile file) {
        try {
            FileOcrModel model = new FileOcrModel();
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            String uuid = uuid();
            String filePath = uploadPath + uuid + "." + fileType;
            model.setUuid(uuid);
            model.setFileName(fileName);
            model.setFileType(fileType);
            model.setFileSize(file.getSize() / 1024 + "KB");
            model.setFileSaveUrl(filePath);
            File fileSave = new File(filePath);
            file.transferTo(fileSave);
            return model;
        } catch (IOException e) {
            throw new RuntimeException("save file[" + file.getOriginalFilename() + "] failed...cuase:", e);
        }
    }

}
